package com.cloud.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 创建桶策略
 *
 * @author yzj
 */
public class PolicyJsonUtils {

    /**
     * Json转String
     *
     * @param path       文件路径
     * @param bucketName 这里是传入的桶名称，执行完后会替换掉原json文件中的 MybuckerName
     * @return
     */
    public static String JsonToString(String path, String bucketName) {
        StringBuilder result = new StringBuilder();
        try {
            ClassPathResource resource = new ClassPathResource(path);
            InputStream in = resource.getInputStream();
            // 读取文件上的数据。将字节流向字符流的转换。
            InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
            // 创建字符流缓冲区
            BufferedReader bufr = new BufferedReader(isr);
            String line = null;
            while ((line = bufr.readLine()) != null) {
                result.append(System.lineSeparator() + line);
            }
            isr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject parse = (JSONObject) JSONObject.parse(result.toString());
        JSONArray statement = (JSONArray) parse.get("Statement");
        JSONObject o = (JSONObject) statement.get(0);
        o.remove("Resource");
        o.fluentPut("Resource", "arn:aws:s3:::" + bucketName);
        JSONObject o1 = (JSONObject) statement.get(1);
        o1.remove("Resource");
        o1.fluentPut("Resource", "arn:aws:s3:::" + bucketName + "/*");
        return parse.toString();
    }

}
